package edu.yuhf.service;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.yuhf.db.utils.TransactionManager;

import edu.yuhf.dao.UserJdbcDaoImpl;
import edu.yuhf.dao.iface.UserDao;
import edu.yuhf.domain.Page;
import edu.yuhf.domain.UMQueryKeyword;
import edu.yuhf.domain.User;
import edu.yuhf.domain.UserDetail;
import edu.yuhf.service.iface.UserService;

public class UserServiceImpl implements UserService{

	private UserDao userDao=new UserJdbcDaoImpl();
	private static Logger log=Logger.getLogger(UserServiceImpl.class);
	
	@Override
	public boolean login(String name, String password) {
		boolean flag=false;
		if(userDao.checkUser(name, password)==1) {
			flag=true;
		}
		return flag;
	}

	@Override
	public boolean register(User user, UserDetail ud) {
		boolean flag=false;
		int userId=0;
		int rowNum=0;
		TransactionManager tm=new TransactionManager();
		try {
			tm.beginTranscation();
			userId=userDao.insertUser(user);
			ud.setUserId(userId);
			rowNum=userDao.insertUserDetail(ud);
			tm.commitAndClose();
		}catch(Exception e) {
			log.error("insert into User error, message is "+e.getMessage());
			tm.rollbackandClose();
		}
		if(userId!=-1&&rowNum!=0) {
			flag=true;
		}
		return flag;
	}

	@Override
	public List<Map<String, Object>> showAll() {
		return userDao.queryAll();
	}

	@Override
	public boolean removeUsers(String ids) {
		boolean flag=false;
		if(userDao.deleteUserDetail(ids)>0){
			if(userDao.deleteUsers(ids)>0) {
				flag=true;
			}
		}
		return flag;
	}

	@Override
	public Map<String, Object> showUserById(String id) {
		return userDao.queryUserById(id);
	}

	@Override
	public boolean updateUser(User user, UserDetail ud) {
		boolean flag=false;
		int userRowNum=0;
		int userDetailRowNum=0;
		TransactionManager tm=new TransactionManager();
		try {
			tm.beginTranscation();
			userRowNum=userDao.updateUser(user);
			userDetailRowNum=userDao.updateUserDetail(ud);
			tm.commitAndClose();
		}catch(Exception e) {
			log.error("update User error, message is "+e.getMessage());
			tm.rollbackandClose();
		}
		if(userRowNum==1&&userDetailRowNum==1) {
			flag=true;
		}
		return flag;
	}

	@Override
	public void showByPage(Page<List<Map<String, Object>>> page) {
		userDao.queryByPage(page);
	}

	@Override
	public void getTotalRow(Page<List<Map<String, Object>>> page) {
		userDao.getTotalRow(page);
	}

	@Override
	public void showByPage(Page<List<Map<String, Object>>> page, UMQueryKeyword qk) {
		userDao.queryByPage(page,qk);
		
	}

	@Override
	public void getTotalRow(Page<List<Map<String, Object>>> page, UMQueryKeyword qk) {
		userDao.getTotalRow(page,qk);
		
	}

}
